import md5 from "js-md5"
import Vue from 'vue'
export default {
  namespaced: true,
  state: () => ({
    cart: []
  }),
  getters: {
    total(state) {
      let c = 0;
      console.log(12313, state.cart)
      state.cart.forEach(item => {
        item.Goods.forEach(goods => c = c + 1)

      })
      console.log(12313, c)
      return c;
    },
    checkTotal(state) {
      let c = 0;
      state.cart.forEach(x => {
        c += x.Goods.filter(y => y.isCheck).reduce((total, item) => total += item.Goods_amount,
          0);
        console.log(c)
      })
      return c
    },
    dataCode(state) {
      let carLts = [];
      state.cart.forEach(x => {
        x.Goods.forEach(y => {
          if (y.isCheck) {
            var obj = new Object({
              I: y.Goods_id,
              C: y.Goods_amount
            });
            carLts.push(obj);
          }
        })
      })
      return carLts;
    },
    //计算选中商品总价
    checkedGoodsAmount(state) {
      console.log('price', state.cart)
      // .reduce((total, item) => total += item.Goods_amount * item.Goods_price, 0)
      let c = 0;
      state.cart.forEach(x => {
        c += x.Goods.filter(y => y.isCheck).reduce((total, item) => total += item.Goods_amount * item.Goods_price,
          0);
        console.log(c)
      })
      return c.toFixed(2)
    }
  },
  mutations: {
    change_cart(state, {
      data
    }) {
      state.cart = data;
    },
    //全选反选
    updateAllGoodsState(state, newState) {
      // 循环更新购物车中每件商品的勾选状态
      state.cart.forEach(x => x.Goods.forEach(y => y.isCheck = newState))

    },
    //单个商品选中
    updataSignGoodsStatus(state, goodsid) {
      state.cart.forEach(x => {
        x.Goods.forEach(y => {
          if (y.Goods_id == goodsid) {
            y.isCheck = !y.isCheck;
          }
        })
      })
    }
  },
  actions: {
    //购物车查询
    async _querywebcartgoods({
      commit
    }) {
      if (uni.getStorageSync('userinfo')) {
        const uid = JSON.parse(uni.getStorageSync('userinfo')).userId;
        const signMd5 = md5(`Bid=65&UserId=${uid}&key=C63A39419CE64F258ADFE3FAF5E63477`);;
        const result = await uni.$http.get(
          `/WebApi/Wap/Action?t=querywebcartgoods&data=${JSON.stringify({Bid:65,UserId:uid,Sign:signMd5})}`
        )
        const {
          data
        } = result
        console.log('778', data);
        if (data.code == 0) {

          data.data.forEach(item => {
            console.log(item.Goods)
            item.Goods.forEach(obj => {
              Vue.set(obj, 'isCheck', false)
            })
          })
          commit('change_cart', {
            data: data.data.filter(x => x.Class_id != 0)
          })

        }
      }

    },


    //加入购物车
    async AddWebCartGoods({
      dispatch
    }, {
      beGivenUserId,
      goodsId,
      count
    }) {
      const uid = JSON.parse(uni.getStorageSync('userinfo')).userId;
      const signMd5 = md5(
        `beGivenUserId=${beGivenUserId}&Bid=65&count=${count}&goodsId=${goodsId}&UserId=${uid}&key=C63A39419CE64F258ADFE3FAF5E63477`
      );
      const result = await uni.$http.get(
        `/WebApi/Wap/Action?t=addwebcartgoods&data=${JSON.stringify({Bid:65,UserId:uid,Sign:signMd5,beGivenUserId:beGivenUserId,count:count,goodsId:goodsId})}`
      )
      const {
        data
      } = result;
      console.log('add', result)
      if (data.code != 0) {
        uni.showModal({
          content: data.msg
        });
      } else if (data.code == 0) {
        uni.showToast({
          title: '加入购物车成功!',
          duration: 2000
        });
      }
      dispatch('_querywebcartgoods');
    },
    //购物车按钮减一
    async DeductWebCartGoods({
      dispatch
    }, {
      beGivenUserId,
      goodsId
    }) {
      const uid = JSON.parse(uni.getStorageSync('userinfo')).userId;
      const signMd5 = md5(
        `beGivenUserId=${beGivenUserId}&Bid=65&goodsId=${goodsId}&UserId=${uid}&key=C63A39419CE64F258ADFE3FAF5E63477`
      );
      const result = await uni.$http.get(
        `/WebApi/Wap/Action?t=deductwebcartgoods&data=${JSON.stringify({Bid:65,UserId:uid,Sign:signMd5,beGivenUserId:beGivenUserId,goodsId:goodsId})}`
      )
      const {
        data
      } = result;
      console.log('add', result)
      if (data.code != 0) {
        uni.showModal({
          content: data.msg
        });
      } else if (data.code == 0) {

      }
      dispatch('_querywebcartgoods');
    },
    //删除购物车
    async RemoveWebCartGoods({
      dispatch
    }, {
      beGivenUserId,
      goodsId
    }) {
      const uid = JSON.parse(uni.getStorageSync('userinfo')).userId;
      const signMd5 = md5(
        `beGivenUserId=${beGivenUserId}&Bid=65&goodsId=${goodsId}&UserId=${uid}&key=C63A39419CE64F258ADFE3FAF5E63477`
      );
      const result = await uni.$http.get(
        `/WebApi/Wap/Action?t=removewebcartgoods&data=${JSON.stringify({Bid:65,UserId:uid,Sign:signMd5,beGivenUserId:beGivenUserId,goodsId:goodsId})}`
      )


      console.log('delect', result)
      const {
        data
      } = result;

      if (data.code != 0) {
        uni.showModal({
          content: data.msg
        });
      } else if (data.code == 0) {
        uni.showToast({
          title: '删除成功!',
          duration: 2000
        });
        dispatch('_querywebcartgoods');
      }
    }

  }
}
